package com.iaiai.cobra.web.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.iaiai.cobra.common.util.JsonUtil;
import com.iaiai.cobra.common.util.Md5;
import com.iaiai.cobra.common.util.StringUtil;
import com.iaiai.cobra.common.vo.ResultVo;
import com.iaiai.cobra.core.BaseController;
import com.iaiai.cobra.repository.bean.User;
import com.iaiai.cobra.web.vo.OnlineVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with LoginController.
 * Package: com.iaiai.cobra.web.controller
 * Author: iaiai
 * Create Time: 2024/6/22 18:11
 * QQ: 176291935
 * Email: 176291935@qq.com
 * Description:
 */
@RestController
@RequestMapping
@Slf4j
public class LoginController extends BaseController {

    @PostMapping("/login.do")
    public ResultVo login(@RequestBody User params) throws Exception {
        if(params==null
                || StringUtils.isEmpty(params.getAccount())
                || StringUtils.isEmpty(params.getPassword())){
            return fail("参数异常");
        }

        User user = serviceManager.userService.queryAccount(params.getAccount());
        if(user==null){
            return fail("无此用户");
        }

        String password = String.format("%s%s%s",projectConfig.getPasswordPrefix(),params.getPassword(),projectConfig.getPasswordSuffix());
        password = Md5.encrypt(password);

        if(!user.getPassword().equals(password)){
            return fail("密码错误");
        }

        //登录成功，生成token
        String token = StringUtil.get32UUID();

        user.setPassword(null); //密码不允许看到处理
        OnlineVo onlineVo = new OnlineVo();
        onlineVo.setUser(user);
        onlineVo.setCreateTime(new Date());
        serviceManager.redisAdminCache.setLogin(token,user.getId().toString(), JsonUtil.getInstance().serialize(onlineVo));

        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",user);
        return success(map);
    }

    @PostMapping("/logout.do")
    public ResultVo logout() throws Exception {
        OnlineVo onlineVo = getOnline();
        String token = getToken();
        Long userId = onlineVo.getUser().getId();

        serviceManager.redisAdminCache.removeLogin(token,userId.toString());
        serviceManager.redisOnlineCache.removeOnline(token,userId);
        return success();
    }

}
